package com.iqilu.ksd.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ImageView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.R;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.StartAdInfo;
import com.iqilu.ksd.utils.BaseUtils;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.view.MyVideoView;
import com.jude.swipbackhelper.SwipeBackHelper;

import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

/**
 * Created by Coofee on 2016/10/11.
 */

public class StartActivity extends BaseActivity {

    private static final String TAG = "StartActivity";

    private int num = 0;
    private Timer timer;
    private TimerTask timerTask;

    private String startVideo;

    private MyVideoView vvStart;
    private SimpleDraweeView imgAD;
    private Button btAD;
    private ImageView imgCover;

    private boolean isFileExists = false;
    private Boolean showGuide = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        SwipeBackHelper.getCurrentPage(this).setSwipeBackEnable(false);
        startVideo = "android.resource://" + getPackageName() + "/" + R.raw.start;
        vvStart = getView(R.id.vv_start);
        imgAD = getView(R.id.img_ad);
        btAD = getView(R.id.bt_ad);
        imgCover = getView(R.id.img_cover);
        btAD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopCount();
                jumpToMain();
            }
        });

        showGuide = SPUtils.getPref(StartActivity.this,Config.SHOW_GUIDE,true);
        if(TextUtils.isEmpty(SPUtils.getPref(this,Config.PHONE_UUID,""))) {
            SPUtils.setPref(this,Config.PHONE_UUID,UUID.randomUUID().toString().replace("-",""));
        }

        ViewGroup.LayoutParams params = vvStart.getLayoutParams();
        params.height = ScreenUtils.getScreenWidth(this) * 960 / 720;
        vvStart.setLayoutParams(params);
        vvStart.setVideoURI(Uri.parse(startVideo));
        vvStart.start();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                imgCover.setVisibility(View.GONE);
            }
        },500);

        hashLogin();
        showLanuchAd();
        startCount();
    }

    private void jump2guide(){
        stopCount();
        SPUtils.setPref(this,Config.SHOW_GUIDE,false);
        startActivity(new Intent(this,GuideActivity.class));
        finish();
    }

    private void showLanuchAd() {
        String startAdMd5 = SPUtils.getPref(this, StartAdInfo.START_AD_MD5, "sjs5566");
        String localAdImg = CacheUtils.getCacheDir(this) + startAdMd5 + ".jpg";
        if(!FileUtils.isFileExists(localAdImg)){
            localAdImg = CacheUtils.getCacheDir(this) + startAdMd5 + ".gif";
        }
        if (!FileUtils.isFileExists(localAdImg) && !showGuide) {
            isFileExists = false;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    jumpToMain();
                }
            }, 2000);
        } else {
            isFileExists = true;
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setUri(Uri.parse("file://" + localAdImg))
                    .setAutoPlayAnimations(true)
                    .build();
            imgAD.setController(controller);
//            imgAD.setImageURI(Uri.parse("file://" + localAdImg));
            imgAD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String url = SPUtils.getPref(StartActivity.this, StartAdInfo.START_AD_URL, "");
                    String title = SPUtils.getPref(StartActivity.this, StartAdInfo.START_AD_TITLE, "");
                    String shareIcon = SPUtils.getPref(StartActivity.this, StartAdInfo.START_AD_SHARE_ICON, "");
                    if (TextUtils.isEmpty(url)) {
                        return;
                    }
                    stopCount();
                    Intent intent = new Intent(StartActivity.this, ADActivity.class);
                    intent.putExtra("fromStart", true);
                    intent.putExtra("adUrl", url);
                    intent.putExtra("type", NewsType.AD);
                    intent.putExtra("title", title);
                    intent.putExtra("shareicon", shareIcon);
                    startActivity(intent);
                    finish();
                }
            });
        }
    }

    public void startCount() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (num < 9) {
                    num++;
                    Message message = new Message();
                    message.arg1 = num;
                    handler.sendMessage(message);
                }
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void stopCount() {
        if (timer != null) {
            timer.cancel();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int num = msg.arg1;
            Log.i(TAG,"num====>"+num);
            if(num == 3 && showGuide){
                Log.i(TAG,"jump2guide");
                jump2guide();
                return;
            }
            if (num > 3 && isFileExists && !showGuide) {
                btAD.setText(String.format(getResources().getString(R.string.jump_ad), "" + (7 - num)));
                btAD.setVisibility(View.VISIBLE);
                if (imgAD.getVisibility() == View.GONE) {
                    AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
                    animation.setDuration(500);
                    imgAD.startAnimation(animation);
                    imgAD.setVisibility(View.VISIBLE);
                }
                if (num > 6) {
                    jumpToMain();
                }
            }
        }
    };

    public void jumpToMain() {
        startActivity(new Intent(this, MainActivity.class));
        stopCount();
        finish();
    }
}
